import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth' // Import the auth store

import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import CustomerDashboardView from '../views/customer/CustomerDashboardView.vue'
import EmployeeDashboardView from '../views/employee/EmployeeDashboardView.vue'
import AdminDashboardView from '../views/admin/AdminDashboardView.vue'
import MeetingRoomManagementView from '../views/admin/MeetingRoomManagementView.vue'
import UserManagementView from '../views/admin/UserManagementView.vue'
import ReservationManagementView from '../views/admin/ReservationManagementView.vue'
import CancellationRequestView from '../views/customer/CancellationRequestView.vue'
import CancellationApprovalView from '../views/employee/CancellationApprovalView.vue'
import MeetingRoomStatusView from '../views/employee/MeetingRoomStatusView.vue'
import BookRoomView from '../views/customer/BookRoomView.vue'
import ProfileView from '../views/customer/ProfileView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { guestOnly: true },
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
      meta: { guestOnly: true },
    },
    {
      path: '/customer/meeting-rooms',
      name: 'customer-meeting-rooms',
      component: () => import('../views/customer/MeetingRoomsView.vue'),
      meta: { requiresAuth: true, allowedRoles: ['Customer'] },
    },
    {
      path: '/customer/dashboard',
      name: 'customer-dashboard',
      component: CustomerDashboardView,
      meta: { requiresAuth: true, allowedRoles: ['Customer'] },
    },
    {
      path: '/customer/reservations',
      name: 'customer-reservations',
      component: ReservationManagementView,
      meta: { requiresAuth: true, allowedRoles: ['Customer'] },
    },
    {
      path: '/customer/book-room',
      name: 'customer-book-room',
      component: BookRoomView,
      meta: { requiresAuth: true, allowedRoles: ['Customer'] },
    },
    {
      path: '/customer/cancel-request',
      name: 'customer-cancel-request',
      component: CancellationRequestView,
      meta: { requiresAuth: true, allowedRoles: ['Customer'] },
    },
    {
      path: '/customer/profile',
      name: 'customer-profile',
      component: ProfileView,
      meta: { requiresAuth: true, allowedRoles: ['Customer'] },
    },
    {
      path: '/employee/dashboard',
      name: 'employee-dashboard',
      component: EmployeeDashboardView,
      meta: { requiresAuth: true, allowedRoles: ['Employee'] },
    },
    {
      path: '/employee/meeting-room-status',
      name: 'employee-meeting-room-status',
      component: MeetingRoomStatusView,
      meta: { requiresAuth: true, allowedRoles: ['Employee'] },
    },
    {
      path: '/employee/cancellation-approval',
      name: 'employee-cancellation-approval',
      component: CancellationApprovalView,
      meta: { requiresAuth: true, allowedRoles: ['Employee'] },
    },
    {
      path: '/employee/reservations',
      name: 'employee-reservations',
      component: ReservationManagementView,
      meta: { requiresAuth: true, allowedRoles: ['Employee'] },
    },
    {
      path: '/admin/dashboard',
      name: 'admin-dashboard',
      component: AdminDashboardView,
      meta: { requiresAuth: true, allowedRoles: ['Admin'] },
    },
    {
      path: '/admin/users',
      name: 'admin-users',
      component: UserManagementView,
      meta: { requiresAuth: true, allowedRoles: ['Admin'] },
    },
    {
      path: '/admin/meeting-rooms',
      name: 'admin-meeting-rooms',
      component: MeetingRoomManagementView,
      meta: { requiresAuth: true, allowedRoles: ['Admin'] },
    },
    // Catch-all route for 404 - always last
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      redirect: '/login', // Redirect to login for any unmatched routes
    },
  ],
})

router.beforeEach(async (to, from, next) => {
  console.log('Navigation from', from.path, 'to', to.path)
  const authStore = useAuthStore()

  try {
    const isAuthenticated = await authStore.checkAuth()
    console.log('Auth check result:', isAuthenticated)
    const userRole = authStore.userRole()

    if (to.meta.requiresAuth) {
      if (!isAuthenticated) {
        console.log('Redirecting to login - not authenticated')
        next({ name: 'login', query: { redirect: to.path } })
        return
      }

      // Check roles
      if (to.meta.allowedRoles && !to.meta.allowedRoles.includes(userRole)) {
        // Redirect to role-specific dashboard
        const dashboardRoute =
          {
            Admin: 'admin-dashboard',
            Employee: 'employee-dashboard',
            Customer: 'customer-dashboard',
          }[userRole] || 'login'

        next({ name: dashboardRoute })
        return
      }
    } else if (to.meta.guestOnly && isAuthenticated) {
      // Redirect authenticated users away from guest-only pages
      const dashboardRoute =
        {
          Admin: 'admin-dashboard',
          Employee: 'employee-dashboard',
          Customer: 'customer-dashboard',
        }[userRole] || 'login'

      next({ name: dashboardRoute })
      return
    }

    next()
  } catch (error) {
    console.error('Error during navigation guard:', error)
    next({ name: 'login' })
  }
})

export default router
